package com.example.demofx.master;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.layout.VBox;
import javafx.scene.control.ScrollPane;
import javafx.stage.Stage;
import javafx.scene.Node;

import java.util.stream.Collectors;

public class TableAndPaginationCreator {
    private ObservableList<Contact> allData;//当前显示的联系人数据列表
    private int itemsPerPage;//每页显示的联系人数量
    public Pagination pagination;//分页器组件
    private ContactManager contactManager;
    private ContactSavedListener contactSavedListener;
    private GroupManager groupManager;

    public TableAndPaginationCreator(ObservableList<Contact> allData, int itemsPerPage, ContactManager contactManager, ContactSavedListener listener, GroupManager groupManager) {
        this.allData = FXCollections.observableArrayList(allData);
        this.itemsPerPage = itemsPerPage;
        this.contactManager = contactManager;
        this.contactSavedListener = listener;
        this.groupManager = groupManager;
    }

    public ObservableList<Contact> getAllData() {
        return allData;
    }

    public VBox createTableAndPagination() {
        VBox centerLayout = new VBox(10);
        pagination = new Pagination();
        updatePagination();
        if (allData.size() > 0) {
            centerLayout.getChildren().addAll(pagination);
        }
        return centerLayout;
    }

//    public void updateAllData() {
//        ObservableList<Contact> newData = contactManager.getAllContacts();
//        allData.setAll(newData);
//    }

    public void updateData(ObservableList<Contact> newData) {
        System.out.println("\n=== 开始更新表格数据 ===");
        System.out.println("TableAndPaginationCreator: 开始更新数据，新数据大小: " + newData.size());
        System.out.println("当前表格数据大小: " + allData.size());
        
        try {
            allData.setAll(newData);
            System.out.println("TableAndPaginationCreator: 数据已更新，当前大小: " + allData.size());
            
            System.out.println("开始更新分页器");
            updatePagination();
            System.out.println("分页器更新完成");
        } catch (Exception e) {
            System.err.println("更新表格数据时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
        System.out.println("=== 表格数据更新完成 ===\n");
    }

    private Node createPage(int pageIndex) {
        // 检查 allData 是否为空，若为空则返回空的 ScrollPane
        if (allData.isEmpty()) {
            return new ScrollPane();
        }

        int fromIndex = pageIndex * itemsPerPage;
        int toIndex = Math.min(fromIndex + itemsPerPage, allData.size());

        TableView<Contact> tableView = new TableView<>();
        tableView.getColumns().addAll(
                getSelectColumn(),
                getNameColumn(),
                getPhoneColumn(),
                getEmailColumn(),
                getGroupColumn(),
                getStarredColumn()
        );

        tableView.setItems(FXCollections.observableArrayList(allData.subList(fromIndex, toIndex)));
        tableView.getColumns().forEach(column -> column.setPrefWidth(150));
        tableView.setEditable(true);

        // 设置表格的固定高度
        double rowHeight = 30.0; // 每行的高度
        double headerHeight = 30.0; // 表头的高度
        tableView.setFixedCellSize(rowHeight);
        tableView.setPrefHeight(headerHeight + (toIndex - fromIndex) * rowHeight);

        // 添加行点击事件监听器
        tableView.setRowFactory(tv -> {
            TableRow<Contact> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 1 && (!row.isEmpty())) {
                    Contact selectedContact = row.getItem();
                    if (selectedContact != null) {
                        ContactWindow contactWindow = new ContactWindow(contactManager);
                        contactWindow.setCurrentContact(selectedContact);
                        contactWindow.setContactSavedListener(contactSavedListener);
                        contactWindow.start(new Stage());
                    }
                }
            });
            return row;
        });

        ScrollPane scrollPane = new ScrollPane(tableView);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);
        scrollPane.setPrefHeight(tableView.getPrefHeight() + 2); // 加上边框的高度

        return scrollPane;
    }

    public void updatePagination() {
        int pageCount = allData.isEmpty() ? 0 : (int) Math.ceil((double) allData.size() / itemsPerPage);
        pagination.setPageCount(pageCount);
        pagination.setPageFactory(this::createPage);
    }

//    public void selectAll(boolean isSelected) {
//        for (Contact contact : allData) {
//            contact.setSelected(isSelected); // 设置选中状态
//        }
//        updatePagination(); // 更新分页器以反映更改
//    }

    private TableColumn<Contact, Boolean> getSelectColumn() {
        TableColumn<Contact, Boolean> selectColumn = new TableColumn<>("选择");
        selectColumn.setCellValueFactory(cellData -> cellData.getValue().selectedProperty());
        selectColumn.setCellFactory(CheckBoxTableCell.forTableColumn(selectColumn));
        return selectColumn;
    }

    private TableColumn<Contact, String> getNameColumn() {
        TableColumn<Contact, String> nameColumn = new TableColumn<>("姓名");
        nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
        return nameColumn;
    }

    private TableColumn<Contact, String> getEmailColumn() {
        TableColumn<Contact, String> emailColumn = new TableColumn<>("邮箱地址");
        emailColumn.setCellValueFactory(cellData -> cellData.getValue().emailProperty());
        return emailColumn;
    }

    private TableColumn<Contact, String> getPhoneColumn() {
        TableColumn<Contact, String> phoneColumn = new TableColumn<>("手机号码");
        phoneColumn.setCellValueFactory(cellData -> cellData.getValue().mobileProperty());
        return phoneColumn;
    }

    private TableColumn<Contact, String> getGroupColumn() {
        TableColumn<Contact, String> groupColumn = new TableColumn<>("所在分组");

        // 分组显示逻辑
        groupColumn.setCellValueFactory(cellData -> {
            Contact contact = cellData.getValue();
            // 将组的集合转换为逗号分隔的字符串
            String groupNames = contact.getGroups().stream()
                    .map(Group::getGroupName)
                    .collect(Collectors.joining(", "));

            return new SimpleStringProperty(groupNames.isEmpty() ? "无分组" : groupNames);
        });

        return groupColumn;
    }

    private void showGroupEditDialog(Contact contact) {
        // 创建分组选择对话框
        Dialog<ObservableList<Group>> dialog = new Dialog<>();
        dialog.setTitle("修改分组");
        dialog.setHeaderText("为 " + contact.getName() + " 选择分组");

        // 创建分组选择控件（这里需要根据你的实际UI组件实现）
        ContactManager contactManager = new ContactManager();
        ListView<Group> groupListView = new ListView<>(groupManager.getAllGroups(contactManager));
        groupListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        groupListView.getSelectionModel().selectAll();

        dialog.getDialogPane().setContent(groupListView);
        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        dialog.setResultConverter(buttonType -> {
            if (buttonType == ButtonType.OK) {
                return FXCollections.observableArrayList(
                        groupListView.getSelectionModel().getSelectedItems()
                );
            }
            return null;
        });

        // 显示对话框并处理结果
        dialog.showAndWait().ifPresent(selectedGroups -> {
            contact.setGroups(selectedGroups);
            contactManager.updateContact(contact);
            refreshTable(); // 刷新表格显示
        });
    }


    public void refreshTable() {
        ObservableList<Contact> newData = contactManager.getAllContacts();
        updateData(newData); // 更新数据
        updatePagination(); // 更新分页器
    }

    private TableColumn<Contact, Boolean> getStarredColumn() {
        TableColumn<Contact, Boolean> starredColumn = new TableColumn<>("收藏");
        starredColumn.setCellValueFactory(cellData -> cellData.getValue().starredProperty());

        starredColumn.setCellFactory(column -> {
            return new TableCell<Contact, Boolean>() {
                @Override
                protected void updateItem(Boolean item, boolean empty) {
                    super.updateItem(item, empty);

                    if (item == null || empty) {
                        setText(null);
                        setStyle("");
                    } else {
                        setText(item ? "是" : "否");
                        setStyle(item ? "-fx-text-fill: #388e3c;" : "-fx-text-fill: #757575;");
                    }
                }
            };
        });

        starredColumn.setEditable(false);
        return starredColumn;
    }


    public Pagination getPagination() {
        return pagination;
    }


}